import { getRoleConfig } from "utils/constants/bodyconstant";
import { ATeamEntity } from "..";
import { UpgradeComponent } from "../../room/controller/UpgradeComponent";
import { TaskHelper } from "utils/task/TaskHelper";
import { priority } from "utils/constants/definetypes";
import { BodyEfficiency } from "utils/creep/bodyEfficiency";
import { CoreEntity } from "../../room/core/CoreEntity";
import { PositionHelper } from "utils/position/PositionHelper";

export class TeamUpgrader extends ATeamEntity<ITeamMemoryUpgrader,ITeamInitializer>
{
    private upgradeComponent!:UpgradeComponent<TeamUpgrader>;
    get teamTimeTickLive(): number {
        return 1500;
    }
    public updateMemory(): void 
    {
        this.update();
    }
    get Controller()
    {
        return this.room.controller as Required<StructureController>
    }
   
    public initAttributes(): void 
    {
        super.initAttributes();
        this.upgradeComponent = new UpgradeComponent(this);
       
        this.upgradeComponent.setRampartPos([]);
        this.update();
    }
   
    private update()
    {
        const cache = this.room.getWorld().PollBlueplan(this.region);
        if(cache)
        {
            // 控制器4格内的container,storage,terminal;
            if(this.room.storage && this.Controller.pos.distance(this.room.storage.pos)<=4)
            {
                this.upgradeComponent.getRoot=(p:IRoomPosition)=> {
                        if(this.room.storage && PositionHelper.isEqual(p,this.room.storage.pos))
                        {
                            return this.room.storage
                        } 
                        if(this.room.terminal && PositionHelper.isEqual(p,this.room.terminal.pos))
                        {
                            return this.room.terminal
                        }
                        return PositionHelper.lookFor(LOOK_STRUCTURES,p).filter(e=>e.structureType == STRUCTURE_CONTAINER)[0] as AnyStoreStructure
                    }
                this.upgradeComponent.initTransferTree([this.room.storage.pos],this.filterValid.bind(this))
            }else 
            {
                const containers = this.room.getStructures(STRUCTURE_CONTAINER).filter(e=>e.pos.distance(this.Controller.pos)<=4);
                if(containers.length>0)
                {
                    const ret = _.sortBy(containers,e=>e.pos.distance(this.
                        Controller.pos));

                    this.upgradeComponent.getRoot=(p:IRoomPosition)=> {
                         return Game.getObjectById(ret[0].id) as AnyStoreStructure  }
                    this.upgradeComponent.initTransferTree([ret[0].pos],this.filterValid.bind(this))
                }
                else 
                {
                    this.log("error","没有容器",`但是却创建了升级模块`)
                }
            }
        }
    }

    private filterValid(pos:IRoomPosition)
    {
        const p1 = this.Controller.pos;
        if(this.room.getTerrain().get(pos.x,pos.y) == TERRAIN_MASK_WALL)
        {
            // 在墙上
            return false;
        }
        if(PositionHelper.lookFor(LOOK_STRUCTURES,pos).filter(e=>e.structureType!== STRUCTURE_ROAD && e.structureType!== STRUCTURE_RAMPART && e.structureType!== STRUCTURE_CONTAINER).length>0)
        {
            return false;
        }
       
        if(PositionHelper.Distance(pos,p1)>3)
        {
            return false;
        }
        const core =  this.getEntity("CoreEntity");
        if(core && PositionHelper.Distance(core.ManagerPosition,pos)<=0)
        {
            return false;
        }
        // source 的两格内也不能放
        const source =  this.getEntitys("InnerMineEntity");
        if(source)
        {
            for(const e of source)
            {
                const positions = e.BasePosition.getFreeSpace(2);
                for(const e of positions)
                {
                    if(PositionHelper.isEqual(pos,e))
                    {
                        return false;
                    }
                }
            }
        }
        return true;
    }
    // 初始化内存
    protected initNodeMemory()
    {
        super.initNodeMemory();
        const memory = this.getNodeMemory();
        if(!memory.required)
        {
            memory.required=[
                [{
                  Role:"upgrader" ,
                  body:getRoleConfig("upgrader",this.room.controller.level as number).body,
                }
                ,1
                ]
            ];
          
        }
 

    }


    public getWorkProgress()
    {
        return BodyEfficiency.getWorkProgress(this.creeps,"upgradeController")
    }
    /**
     * 投递孵化爬的任务
     */
    public postSpawn(inpriority:number = priority.F): void 
    {
        const spawnentity = this.getEntity("SpawnEntity");

        

        if( spawnentity.getTasksByOwner(this.GUID()))
        {
            //this.log("warn","postSpawn",`投递孵化任务`,'失败') 
            return 
        }
       
        const task =  this.postSpawnImpl(this.groupCreeps,inpriority);
        if(task)
        {
            task.data.teamid = this.GUID();
           // this.log("warn","postSpawn",`投递孵化任务`,'成功') 
        }
        else 
        {
            //this.log("warn","postSpawn",`投递孵化任务 postSpawnImpl`,'失败') 
        }
    }

    public dowork(room:Room,worker:Creep[])
    {
        this.upgradeComponent.dowork(worker);
        
        this.upgradeComponent.updateEnergyTree(room);
    }
    public maxWorker()
    {
        return this.upgradeComponent.TransferTree.slotCount;
    }
    public get rootStore()
    {
        return this.upgradeComponent.rootStore
    }
    public visual()
    {
        this.upgradeComponent.TransferTree.visual();
    }
}